<?php

namespace DreamCat\FrameCore\Factory\Impl\LoggerFactory;

use Components\Utils\Funcs\FileSystemHelper;
use DreamCat\Container\EntryFactory;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/**
 * 默认的日志记录器工厂方法
 * @author vijay
 */
class DefaultLoggerFactory implements EntryFactory
{
    /**
     * @RootPath
     * @var string 项目根目录
     */
    private $rootPath = "";

    /**
     * @Config log
     * @var array 日志配置
     */
    private $logConfig = [];

    /**
     * @return string 项目根目录
     */
    public function getRootPath(): string
    {
        return $this->rootPath;
    }

    /**
     * @param string $rootPath 项目根目录
     * @return static 对象本身
     */
    public function setRootPath(string $rootPath): DefaultLoggerFactory
    {
        $this->rootPath = $rootPath;
        return $this;
    }

    /**
     * 创建实体
     * @param string $id 实体标识
     * @param string $arg 额外参数
     * @return mixed 实体
     * @throws \Exception
     */
    public function create(string $id, string $arg)
    {
        $logConfig = $this->getLogConfig();
        $logDir = $logConfig["dir"] ?? "cache/logs";
        if (!FileSystemHelper::isAbsolutePath($logDir)) {
            $logDir = "{$this->getRootPath()}/{$logDir}";
        }
        $logger = new Logger($this->getLoggerName());
        if (!isset($logConfig["logs"])) {
            $logConfig["logs"][0] = [
                "fileName" => "default.log",
                "maxFile" => 10,
                "level" => Logger::INFO,
            ];
        }
        foreach ($logConfig["logs"] as $config) {
            $handle = new RotatingFileHandler(
                "{$logDir}/{$config["fileName"]}",
                $config["maxFile"],
                $config["level"]
            );
            $logger->pushHandler($handle);
        }
        if (isset($logConfig["stdout"]) && $logConfig["stdout"]) {
            $logger->pushHandler(new StreamHandler("php://output", $logConfig["stdout"]));
        }
        return $logger;
    }

    /**
     * @return array 日志配置
     */
    public function getLogConfig(): array
    {
        return $this->logConfig;
    }

    /**
     * @param array $logConfig
     * @return static 对象本身
     */
    public function setLogConfig(array $logConfig): DefaultLoggerFactory
    {
        $this->logConfig = $logConfig;
        return $this;
    }

    /**
     * @return string 日志频道名
     */
    protected function getLoggerName(): string
    {
        return $this->logConfig["name"] ?? "runlog";
    }
}

# end of file
